import 'dart:typed_data';

import 'package:binary/binary.dart';
import 'package:inmotion_protocol/common/compact.dart';
import 'package:inmotion_protocol/common/product_model.dart';
import 'package:inmotion_protocol/common/product_version.dart';
import 'package:inmotion_protocol/lorin/bean/scooter/scooter_settings.dart';
import 'package:inmotion_protocol/util/byte_util.dart';

class RsVeloSettings extends ScooterSettings {
  Uint4 onePedalMode = Uint4.zero;
  Uint4 brakeFirstMode = Uint4.zero;

  Uint8 frontAccForce = Uint8.zero;
  Uint8 rearAccForce = Uint8.zero;

  Uint8 frontBrakeForce = Uint8.zero;
  Uint8 rearBrakeForce = Uint8.zero;

  Uint16 standbyTime = Uint16.zero;

  Uint8 autoParkTime = Uint8.zero;

  Uint4 tboxLowBatteryWakeUp = Uint4.zero;

  RsVeloSettings(ProductModel model, VersionWrapper version)
      : super(model, version);

  @override
  void initCompact() {
    compact = DefaultRsVeloSettings();
  }

  @override
  RidingMode toRidingMode(int mode) {
    switch (mode) {
      case 0:
        return RidingMode.p;
      case 2:
        return RidingMode.normal;
      case 3:
        return RidingMode.sport;
      case 4:
        return RidingMode.x;
      case 1:
      default:
        return RidingMode.eco;
    }
  }
}

class DefaultRsVeloSettings extends Compact<RsVeloSettings> {
  @override
  void fromBytes(RsVeloSettings output, Uint8ClampedList bytes, int offset) {
    output.zeroStartupState = ByteUtil.bitValue(bytes[offset], 0, 1);
    output.cruiseState = ByteUtil.bitValue(bytes[offset], 1, 1);
    output.speedUnit = ByteUtil.bitValue(bytes[offset], 2, 1);
    output.ridingMode =
        output.toRidingMode(ByteUtil.bitValue(bytes[offset], 3, 3).value);
    output.lockMode = ByteUtil.bitValue(bytes[offset], 6, 1);
    output.safeSpeedLimitState = ByteUtil.bitValue(bytes[offset], 7, 1);
    offset++;
    output.onePedalMode = ByteUtil.bitValue(bytes[offset], 0, 1);
    // 协议定义0为开，1为关
    output.brakeFirstMode =
        ByteUtil.bitValue(bytes[offset], 1, 1).value == 1 ? Uint4(0) : Uint4(1);
    output.tboxLowBatteryWakeUp = ByteUtil.bitValue(bytes[offset], 2, 1);
    // 剩余5bit保留

    offset++;
    output.frontAccForce = ByteUtil.toUint8(bytes[offset]);
    offset++;
    output.rearAccForce = ByteUtil.toUint8(bytes[offset]);
    offset++;
    output.frontBrakeForce = ByteUtil.toUint8(bytes[offset]);
    offset++;
    output.rearBrakeForce = ByteUtil.toUint8(bytes[offset]);
    offset++;

    output.standbyTime =
        ByteUtil.toUint16(ByteUtil.bytes2Uint16Le(bytes, offset).value * 60);
    offset += 2;

    // 跳过氛围灯
    offset++;
    output.autoParkTime = ByteUtil.toUint8(bytes[offset]);
  }

  @override
  int length() {
    return 10;
  }
}
